﻿using Admin.Models;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Driver;

namespace Admin.Infra
{
    public class Helpers
    {
        public readonly IncludesDBContext includeContext = new IncludesDBContext();

        public void ItemPagination()
        {
            var pageNumber = 1;// current page should come from the client
            var filter = new BaseFilter() { CurrentPage = pageNumber, ItemsPerPage = 30 };
            var items = GetItemsByFilter(filter, Query.LTE("CreatedDate", DateTime.Now), SortBy.Ascending("FileName"));
            var totalCount = filter.TotalCount; // here will be total items count
            var pagesCount = filter.TotalPagesCount; // here will be total pages count
        }

        public List<Include> GetItemsByFilter(BaseFilter filter, IMongoQuery query, SortByBuilder sort)
        {
            var resultItems = new List<Include>();
            var cursor = includeContext.Includes.FindAs<Include>(query);

            cursor.SetSortOrder(sort);
            if (filter.IsNeedPaging)
            {
                cursor.SetSkip(filter.Skip).SetLimit(filter.Take);
                filter.TotalCount = cursor.Count();
            }

            resultItems.AddRange(cursor);

            return resultItems;
        }
    }

    public class BaseFilter
    {
        private int _itemsPerPage = 10;
        private int _skip = 0;
        private int _currentPage = 1;

        public BaseFilter()
        {
            IsNeedPaging = true;
        }

        public int Skip
        {
            get
            {
                if (_skip == 0)
                    _skip = (CurrentPage - 1) * _itemsPerPage;
                return _skip;
            }
            set
            {
                _skip = value;
            }
        }

        public int Take
        {
            get
            {
                return _itemsPerPage;
            }
            set
            {
                _itemsPerPage = value;
            }
        }

        public bool IsNeedPaging { get; set; }

        public long TotalCount { get; set; }

        public int CurrentPage
        {
            get
            {
                return _currentPage;
            }
            set
            {
                _currentPage = value;
            }
        }

        public int ItemsPerPage
        {
            get
            {
                return _itemsPerPage;
            }
            set
            {
                _itemsPerPage = value;
            }
        }

        public long TotalPagesCount
        {
            get
            {
                return TotalCount / ItemsPerPage +
                                 ((TotalCount % ItemsPerPage > 0) ? 1 : 0);
            }
        }
    }
}